<?php
// Secure session handling utilities.
// Part of mmvc library, https://code.google.com/p/mmvc/
// Dependencies: None

/** 
 * Returns hash of the user session identifier data (IP + user agent + secret).
 */
function sesHash( $secret ) {
	// use only lowest part since users behind NAD might have their IP changing almost every request
	$ip = (isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1');
	$ip = explode('.',$ip);
	$ip = ( sizeof($ip) > 1 ? $ip[0].'.'.$ip[1] : substr($ip[0],0,strlen($ip[0])/2) );
	return md5( $secret . (isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:'shell') . $ip );
}

/** 
 * Returns true if the session is still valid. Failed session check might be caused by session hijack attempt.
 */
function sesCheck( $key, $secret ) {
	return isset($_SESSION[$key]) && $_SESSION[$key] == sesHash($secret);
}

/**
 * Starts a session if it has not beed started already.
 * Checks for session validity. Clears all session data if session not valid.
 * @param $key Session key name
 * @param $secret Session secret key
 * @parma $session_name Name of the session / project
 * @param $expire Expire time in minutes
 * @return true if session was valid, false otherwise.
 */
function sesStart( $key, $secret, $session_name, $expire=180 ) {
	global $g_sesStarted;
	if ( !isset($g_sesStarted) ) {
		session_cache_expire($expire);
		session_name( $session_name );
		session_start();
		$g_sesStarted = 1;
	}
	$valid = sesCheck($key,$secret); 
	if ( !$valid ) {
		sesNew( $key, $secret );
		foreach (array_keys($_SESSION) as $k)
			unset( $_SESSION[$k] );
	}
	return $valid;
}

/**
 * Creates new session.
 * @param $key Session key name
 * @param $secret Session secret key
 */
function sesNew( $key, $secret ) {
	$_SESSION[$key] = sesHash( $secret );
	session_regenerate_id( true );
}

?>